package com.lz.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET = "mySecretKey"; // 密钥


    /**
     * 从JWT中提取用户名
     * @param token JWT Token
     * @return 用户名
     */
    public static String getUsernameFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            // 从JWT的声明中获取用户名
            String username = jwt.getClaim("username").asString();
            System.out.println("Extracted username: " + username);
            return username;
        } catch (JWTVerificationException e) {
            throw new RuntimeException("Invalid token", e);
        }
    }

    // 生成JWT
    public static String createToken(String username) {
        Date issuedAt = new Date();
        Date expiresAt = new Date(issuedAt.getTime() + 60 * 1000);

        return JWT.create()
                .withIssuer("auth0") // 设置签发者
                .withClaim("username", username) // 添加自定义声明
                .withClaim("roles", username) // 添加角色
                .withIssuedAt(issuedAt) // 设置签发时间
                .withExpiresAt(expiresAt) // 设置过期时间
                .sign(Algorithm.HMAC256(SECRET)); // 使用HMAC256算法签名
    }


    // 生成JWT
    public String createToken(Map<String, String> payload, long validityPeriodMillis) {
        Date issuedAt = new Date();
        Date expiresAt = new Date(issuedAt.getTime() + validityPeriodMillis);

        return JWT.create()
                .withIssuer("auth0") // 设置签发者
                .withClaim("username", payload.get("username")) // 添加自定义声明
                .withClaim("roles", payload.get("roles")) // 添加角色
                .withIssuedAt(issuedAt) // 设置签发时间
                .withExpiresAt(expiresAt) // 设置过期时间
                .sign(Algorithm.HMAC256(SECRET)); // 使用HMAC256算法签名
    }


    // 解析JWT
    public Map<String, Claim> decodeToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (TokenExpiredException e) {
            throw new RuntimeException("Token has expired", e);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("Invalid token", e);
        }
    }
}